package com.fenghongzhang.module_main.ui.moto

import MotoCircleNavigationItem
import android.graphics.Color
import android.graphics.Paint
import androidx.fragment.app.viewModels
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.launcher.ARouter
import com.fenghongzhang.lib_core.base.BaseFragment
import com.fenghongzhang.lib_core.base.observeWithLifecycle
import com.fenghongzhang.lib_core.cons.IntentData
import com.fenghongzhang.lib_core.state.Failed
import com.fenghongzhang.lib_core.state.Success
import com.fenghongzhang.lib_core.state.UILoader
import com.fenghongzhang.lib_core.state.UIState
import com.fenghongzhang.lib_core.utils.Router
import com.fenghongzhang.lib_core.utils.ToastUtils
import com.fenghongzhang.lib_core.utils.tintDrawable
import com.fenghongzhang.module_main.R
import com.fenghongzhang.module_main.databinding.FragmentMotoCircleV3Binding
import com.fenghongzhang.module_main.databinding.LayoutCustomTabViewBinding
import com.fenghongzhang.module_main.ui.main.viewmodel.MainViewModel
import com.fenghongzhang.module_main.ui.moto.model.MotoCircleModule
import com.fenghongzhang.module_main.ui.post.PostListFragment
import com.google.android.material.tabs.TabLayoutMediator
import com.gyf.immersionbar.ktx.immersionBar
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.observeOn
import kotlinx.coroutines.launch
import javax.inject.Inject

class MotoCircleV3Fragment @Inject constructor() : BaseFragment<MainViewModel, FragmentMotoCircleV3Binding>() {

    override val mLayoutResId: Int = R.layout.fragment_moto_circle_v3

    override val mViewModel: MainViewModel by activityViewModels() //页面viewmodel


    private var mPostAdapter: ScreenSlidePagerAdapter? = null
    private var mSelectedPosition: Int = 0
   // private var popupPublishHelper: PopupPublishHelper? = null
    private var mediator: TabLayoutMediator? = null
    override val mPageCanBack: Boolean
        get() = false

    private lateinit var mUiLoader: UILoader

    private fun initStatusBar() {
        immersionBar {
            this.statusBarDarkFont(true)
            this.statusBarColor(R.color.white)
        }
    }
    override fun initView() {
        initStatusBar()
        initUILoader()
    }



    override fun initListener() {

        mViewModel.navigationState.observeWithLifecycle(this) {
                   handleNavigationData()
        }

        mBinding.lSearch.setOnClickListener {
            ARouter.getInstance().build(Router.Ui.SearchActivity)
                .withString(IntentData.KEY_SEARCH_TYPE, "all")
                .navigation()
//            mTabTitle[1] = Pair("RX6(new)", "00000000000")
//            mPostAdapter?.notifyItemChanged(1)
            //setTabViewStyle(mSelectedPosition)

        }
    }


    private fun handleNavigationData() {
        initViewPager()
    }
    private class ScreenSlidePagerAdapter(private val item: List<MotoCircleNavigationItem>, private val module: MotoCircleModule, fa: Fragment) : FragmentStateAdapter(fa) {

        override fun getItemCount(): Int = item.size

        override fun getItemId(position: Int): Long {
            val navigation = item[position]
            val checkModel = navigation.modelList?.find { it.checked }
            if (checkModel != null) {
                return checkModel.modelId.toLong()
            }
            return item[position].navigationId.toLong()
        }


        override fun createFragment(position: Int): Fragment {
            val navigation = item[position]
            return when (navigation.type) {

                // 热门
                1 -> PostListFragment.newInstance()
                // 帖子
                2 -> PostListFragment.newInstance()
                // 资讯
                3 -> PostListFragment.newInstance()
                // 关注
                4 -> PostListFragment.newInstance()
                else -> {
                    // 关注
                    PostListFragment.newInstance()
                }
            }
        }
    }

    private fun setTabViewStyle(defaultPosition: Int) {
//        mViewModel.mNavigationItem.forEachIndexed { index, _ ->
//            mBinding.tabLayout.run {
//                val binding = getTabAt(index)?.customView?.let {
//                    DataBindingUtil.getBinding<LayoutCustomTabViewBinding>(it)
//                }
//                if (defaultPosition == index) {
//                    binding?.tab?.setTextColor(
//                        ContextCompat.getColor(
//                            requireContext(),
//                            R.color.color_d8000f
//                        )
//                    )
//                    binding?.tab?.paint?.style = Paint.Style.FILL_AND_STROKE
//                    val drawable = ContextCompat.getDrawable(context, R.mipmap.ic_triangle)
//                    //val tintDrawable = tintDrawable(drawable, Color.parseColor("#FFD8000F"))
//                    val tintDrawable = tintDrawable(drawable, Color.parseColor("#FF919191"))
//                    binding?.ivArrow?.setImageDrawable(tintDrawable)
//                    binding?.tab?.paint?.strokeWidth = 0.8f
//                } else {
//                    binding?.tab?.setTextColor(
//                        ContextCompat.getColor(
//                            requireContext(),
//                            R.color.color_101010
//                        )
//                    )
//                    binding?.tab?.paint?.style = Paint.Style.FILL_AND_STROKE
//                    val drawable = ContextCompat.getDrawable(context, R.mipmap.ic_triangle)
//                    val tintDrawable = tintDrawable(drawable, Color.parseColor("#FF919191"))
//                    binding?.ivArrow?.setImageDrawable(tintDrawable)
//                    binding?.tab?.paint?.strokeWidth = 0f
//                }
//
////                mBinding.tabLayout.getTabAt(index)?.view?.let {
////                    //ViewCompat.setPaddingRelative(mBinding.tabLayout.getTabAt(index)?.customView!!, 10.dp, 5.dp, 10.dp, 5.dp)
////                    ViewCompat.setPaddingRelative(it, 5.dp, 0, 5.dp, 0)
////                }
//
//            }
//        }
    }

    private fun initViewPager() {
        //默认选中帖子
        mPostAdapter = ScreenSlidePagerAdapter(mViewModel.mNavigationItem, MotoCircleModule.Post, this)
        mBinding.vp.adapter = mPostAdapter
        //default
        val default = mViewModel.mNavigationItem.find { it.defaultStatus == 1 }
        mSelectedPosition = if (default == null) 0 else mViewModel.mNavigationItem.indexOf(default)
        mBinding.vp.setCurrentItem(mSelectedPosition, false)
        //预加载机制
        mBinding.vp.offscreenPageLimit = 1
        mBinding.vp.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                mSelectedPosition = position
                //设置tablayout的效果
                setTabViewStyle(position)
            }
        })
        mediator = TabLayoutMediator(
            mBinding.tabLayout,
            mBinding.vp,
            true,
            true
        ) { tab, position -> //这里可以自定义TabView
            val tabView = DataBindingUtil.inflate<LayoutCustomTabViewBinding>(
                layoutInflater,
                R.layout.layout_custom_tab_view,
                null,
                false
            )
            if (position >= mViewModel.mNavigationItem.size) {
                return@TabLayoutMediator
            }
            val navigation = mViewModel.mNavigationItem[position]
            tabView.tab.text = navigation.title
            if (navigation.modelList == null || !navigation.modelList.any { it.checked }) {
                tabView.tab.text = mViewModel.mNavigationItem[position].title
            } else {
                tabView.tab.text = navigation.modelList.find { it.checked }?.name
            }
            tabView.ivArrow.visibility = if (navigation.modelList == null) View.GONE else View.VISIBLE
            tabView.lTab.setOnClickListener {
                if (!tab.isSelected) {
                    tab.select()
                    if (navigation.modelList != null) {
                        Handler(Looper.getMainLooper()).postDelayed({
                            showPopupList(
                                tabView.lTab,
                                navigation
                            )
                        }, 400)
                    }
                } else {
                    if (navigation.modelList != null) {
                        showPopupList(tabView.lTab, navigation)
                    }
                }
            }
            tab.customView = tabView.root
        }
        mediator?.attach()

//        TabLayoutMediator(tabLayout, viewPager2) { tab, position ->
//            // 设置页签标题（从适配器中获取）
//            tab.text = adapter.tabTitles[position]
//            // 可选：设置页签图标
//            // tab.setIcon(R.drawable.ic_tab_home)
//        }.attach()  // 必须调用 attach() 才会生效

    }

    override fun initData() {
        mViewModel.getFixedNavigationItem()
    }

    private fun showPopupList(tabView: View, navigation: MotoCircleNavigationItem) {
        //val items = navigation.modelList!!.map { CommonPopupMenu(name = it.name) }
        //   popupMenuRvHelper.bindItems(navigation.navigationId, navigation.modelList!!)
       // popupMenuRvHelper.show(tabView)
    }

    fun initUILoader() {
//        mUiLoader = object : UILoader(requireContext()) {
//            override fun loadSuccessView(container: ViewGroup?): View {
//                return View(context)
//            }
//        }.apply { updateState(UIState.LOADING) }
//
//        mBinding.lContainer.addView(mUiLoader)
    }
}